package com.jt.service.impl;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper mapper;
    @Override
    public String selectUserByUP(User user) {
        //将传进来的密码加密
        byte[] bytes = user.getPassword().getBytes();
        String s = DigestUtils.md5DigestAsHex(bytes);
        //将加密后的密码拿去校验
        user.setPassword(s);
        //根据用户名和密钥查询数据库
        User user1 = mapper.selectUserByUP(user);
        //判断user1是否有值
        if(user1 == null){
            //查询没有数据，返回空
            return null;
        }
        //密钥特点：唯一，迷惑  UUID：几乎保证唯一
        //将UUID中的 - 转为空串
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public PageResult getUserList(PageResult pageResult) {
        //总数
        long total = mapper.findTotal();
        //分页的结果
        int size = pageResult.getPageSize();//条数  http://manage.jt.com/user/list没条件传进来查不到，报空指针
        int start = (pageResult.getPageNum()-1) * size;//起始位置
        String query = pageResult.getQuery();//查询条件
        List<User> userList = mapper.findUserByPage(start,size,query);
        return pageResult.setTotal(total).setRows(userList);
    }

    @Override
    @Transactional
    public void updateStatusById(User user) {
        mapper.updateStatusById(user);
    }

    @Override
    @Transactional
    /*密码加密，状态默认true，创建时间和更新时间*/
    public void addUser(User user) {
        String password = user.getPassword();
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        Date date = new Date();
        user.setPassword(md5Pass).setStatus(true)
                .setCreated(date).setUpdated(date);
        mapper.addUser(user);
    }

    @Override
    public User findUserById(Integer id) {

        return mapper.findUserById(id);
    }

    @Override
    @Transactional
    public void updateUserById(User user) {
        user.setUpdated(new Date());
        mapper.updateUserById(user);
    }

    @Override
    @Transactional
    public void deleteUserById(Integer id) {
        mapper.deleteUserById(id);
    }
}
